#include <func.h>
typedef struct{
    pthread_mutex_t mutex;
    int tickets;
}tick;
void *threadsale1(void *p)
{
    int i=0;
    int last;
    tick *pp=(tick*)p;
    while(1)
    {
        //pthread_mutex_lock(&pp->mutex);//判断前先加锁，就不会出现零票
        if(pp->tickets<=0)
        {
            //pthread_mutex_lock(&pp->mutex);
            //pthread_mutex_unlock(&pp->mutex);
            printf("1 Saled last ticket is %d\nsaled %d tickets\n",last,i);
            break;
        }else
        {
            pthread_mutex_lock(&pp->mutex);
            //printf("1 Saled ticket %d\n",pp->tickets);
            last=pp->tickets--;
            ++i;
            pthread_mutex_unlock(&pp->mutex);
        }
    }
}
void *threadsale2(void *p)
{
    int i=0;
    int last;
    tick *pp=(tick*)p;
    while(1)
    {
        //pthread_mutex_lock(&pp->mutex);
        if(pp->tickets<=0)
        {
            //pthread_mutex_lock(&pp->mutex);
            //pthread_mutex_unlock(&pp->mutex);
            printf("2 Saled last ticket is %d\nsaled %d tickets\n",last,i);
            break;
        }else
        {
            pthread_mutex_lock(&pp->mutex);
            //printf("2 Saled ticket %d\n",pp->tickets);
            last=pp->tickets--;
            ++i;
            pthread_mutex_unlock(&pp->mutex);
        }
    }
}
int main(int argc,char *argv[])
{
    tick tic;
    int ret;
    pthread_t thid1,thid2;
    tic.tickets=10000000;
    ret=pthread_mutex_init(&tic.mutex,NULL);
    THREAD_ERROR_CHECK(ret,"pthread_mutex_t");
    pthread_create(&thid1,NULL,threadsale1,&tic);
    pthread_create(&thid2,NULL,threadsale2,&tic);
    pthread_join(thid1,NULL);
    pthread_join(thid2,NULL);
    return 0;
}

